package com.xpec.c4.service.module.datacenter.player;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.game.itembox.ItemChangeParam;
import com.ms.game.itembox.db.PlayerCrystalChangeLogModel;
import com.ms.game.itembox.db.PlayerItemChangeLogModel;
import com.ms.player.PlayerUserType;
import com.ms.service.error.ErrorCode;
import com.xpec.c4.game.character.PlayerManager;
import com.xpec.c4.game.datamanager.ResultNo;
import com.xpec.c4.service.module.BasicServiceModule;
import com.xpec.c4.service.module.PropertyKey;
import com.xpec.c4.service.module.ServerProperties;
import com.xpec.c4.service.module.datacenter.DCAsyncCommand;

/**
 * 更新玩家道具的異步處理 task
 * 
 * @author TW15010
 */
public class UpdatePlayerItemAsync extends DCAsyncCommand {
	private static final Log log = LogFactory.getLog(UpdatePlayerItemAsync.class);

	PlayerDataManager playerDataManager;
	BasicServiceModule currentModule;

	@Override
	public void asyncExecute() {
		ItemChangeParam param = (ItemChangeParam) dataInfo.getData();

		try {
			PlayerManager.getInstance().updatePlayerItemToDB(currentModule, param);
		} catch (RuntimeException e) {
			log.error("cannot update player item: " + param.getPlayerId(), e);
			resultCode = ResultNo.DB_OPERATION_FAILED;
			return;
		}

		if (param.getResult() == ErrorCode.SUCCESS) {
			resultCode = ResultNo.OK;
		} else {
			resultCode = ResultNo.DB_OPERATION_FAILED;
		}

		return;
	}

	@Override
	public void execute() {
		// callback
		if (playerDataManager != null) {
			playerDataManager.updatePlayerItemToDbCallback(resultCode, dataInfo, srcModuleID);
		}

		boolean isPlayer = ((ItemChangeParam) dataInfo.getData()).getUserType() == PlayerUserType.PLAYER;
		boolean robotNeedToSaveLog = ServerProperties.getBoolean(PropertyKey.robot_save_log, true);
		if (currentModule != null && (isPlayer || robotNeedToSaveLog)) {
			ItemChangeParam param = (ItemChangeParam) dataInfo.getData();
			
			// 寫道具異動 log
			ArrayList<PlayerItemChangeLogModel> itemLogList = param.getLogModelList();
			if (itemLogList != null) {
				for (PlayerItemChangeLogModel logModel : itemLogList) {
					currentModule.saveDbLog(logModel);
				}
			}
			
			PlayerCrystalChangeLogModel crystalChangeLogModel = param.getCrystalChangeLogModel();
			if (crystalChangeLogModel != null) {
				currentModule.saveDbLog(crystalChangeLogModel);
			}
		} // if (currentModule != null)
	}

	public UpdatePlayerItemAsync(PlayerDataManager playerDataManager, BasicServiceModule currentModule) {
		super();
		this.playerDataManager = playerDataManager;
		this.currentModule = currentModule;
	}
}
